package com.project.poetry.common.aspect;

import com.alibaba.fastjson.JSON;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.entity.R;
import com.project.poetry.common.util.CommonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 处理结果
 * @author mengxj
 */
@RestControllerAdvice
public class HandleResponse implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        HttpServletRequest request = CommonUtil.getRequest();
        Object obj = request.getAttribute(ConstantValue.HANDLE_RESPONSE_KEY);
        return ConstantValue.HANDLE_RESPONSE_VALUE.equals(obj);
    }

    @Override
    public Object beforeBodyWrite(Object t, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(Objects.nonNull(t)){
            if(t.getClass() == R.class){
                return t;
            }else{
                if(t instanceof String){
                    return JSON.toJSONString(R.success(t));
                }else{
                    return R.success(t);
                }
            }
        }else{
            return R.success();
        }
    }
}
